package com.example.spsaveqqty;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.spsaveqqty.guides.Guide;
import com.example.spsaveqqty.guides.GuidesMainActivity;
import com.example.spsaveqqty.userManage.User;
import com.example.spsaveqqty.userManage.UserDao;
import com.example.spsaveqqty.userManage.guidesAdapter;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class PersonalCenterActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_username;//用户名
    private TextView tv_location;//地区
    private TextView tv_slogan;//个性签名
    private Button btn_editData;//编辑资料按钮
    private ImageView img_user;//头像

    private ListView lv_guide;
    private guidesAdapter adapter;
    private List<Guide> mguideBeanList;
    private UserDao userdao;
    User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_center_activity);
        //初始化页面：
        //创建userdao对象
        userdao = new UserDao(this);
        requestWritePermission();
        init();

        mguideBeanList  = new ArrayList<>();
        initGuideDate();
        lv_guide = findViewById(R.id.lv_guide_main);
        adapter = new guidesAdapter(mguideBeanList,PersonalCenterActivity.this);
        lv_guide.setAdapter(adapter);

    }

    private void init() {
        tv_username = (TextView) findViewById(R.id.tv_username);
        tv_location = (TextView) findViewById(R.id.tv_location);
        tv_slogan = (TextView) findViewById(R.id.tv_slogan);
        btn_editData = (Button) findViewById(R.id.btn_editData);
        img_user = (ImageView) findViewById(R.id.img_user);
        //设置按钮的点击事件
        btn_editData.setOnClickListener(this);

        tv_slogan.setSelected(true);//用于设置跑马灯
        tv_username.setSelected(true);//用于设置跑马灯
        tv_location.setSelected(true);//用于设置跑马灯

        user = userdao.findUserByUserName(User.USERNAME);
        //设置展示界面上对应的user信息
        //设置头像：
        if (!TextUtils.isEmpty(user.getFlag())){
            if (user.getFlag().equals("1")){		//	相册
                Bitmap bitmap = BitmapFactory.decodeFile(user.getPicture());
                bitmap = Bitmap.createScaledBitmap(bitmap,200,200,true);
                bitmap = toRoundBitmap(bitmap);//调用自己写的方法把bitmap转成圆形
                img_user.setImageBitmap(bitmap);
            }else if (user.getFlag().equals("2")){	//	拍照
                Uri imgUri = Uri.parse(user.getPicture());
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri));
                    bitmap = Bitmap.createScaledBitmap(bitmap,200,200,true);
                    bitmap = toRoundBitmap(bitmap);//调用自己写的方法把bitmap转成圆形
                    img_user.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        tv_username.setText(user.getUsername());
        tv_location.setText(user.getLocation());
        tv_slogan.setText(user.getSlogan());
        if (user.getSex() == 0) {//未填写

        } else if (user.getSex() == 1) {//男
            Drawable drawableRight = getResources().getDrawable(R.drawable.male);
            tv_username.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
//            tv_username.setCompoundDrawablePadding(5);
        } else if (user.getSex() == 2) {//女
            Drawable drawableRight = getResources().getDrawable(R.drawable.female);
            tv_username.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
//            tv_username.setCompoundDrawablePadding(5);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_editData://跳转到编辑资料页面
                Intent intent = new Intent(PersonalCenterActivity.this, EditUserInfoActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.logout_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final Intent intent = new Intent();
        switch (item.getItemId()) {
            case R.id.logout:
                new AlertDialog.Builder(PersonalCenterActivity.this)
                        .setMessage("是否确定退出登录?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //跳转回登录页面
                                Intent intent = new Intent(PersonalCenterActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public Bitmap toRoundBitmap(Bitmap bitmap){
        int width=bitmap.getWidth();
        int height=bitmap.getHeight();
        int r=0;
        //取最短边做边长
        if(width<height){
            r=width;
        }else{
            r=height;
        }
        //构建一个bitmap
        Bitmap backgroundBm=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
        //new一个Canvas，在backgroundBmp上画图
        Canvas canvas=new Canvas(backgroundBm);
        Paint p=new Paint();
        //设置边缘光滑，去掉锯齿
        p.setAntiAlias(true);
        RectF rect=new RectF(0, 0, r, r);
        //通过制定的rect画一个圆角矩形，当圆角X轴方向的半径等于Y轴方向的半径时，
        //且都等于r/2时，画出来的圆角矩形就是圆形
        canvas.drawRoundRect(rect, r/2, r/2, p);
        //设置当两个图形相交时的模式，SRC_IN为取SRC图形相交的部分，多余的将被去掉
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //canvas将bitmap画在backgroundBmp上
        canvas.drawBitmap(bitmap, null, rect, p);
        return backgroundBm;
    }
    //动态申请读取手机内存的权限：
    private void requestWritePermission(){
        //  动态申请WRITE_EXTERNAL_STORAGE 这个危险权限。因为相册中的照片时存储在SD卡上的，我们从SD卡中读取照片就需要申请这个权限
        //  WRITE_EXTERNAL_STORAGE  ——  同时授权程序对SD卡读和写的能力
        if (ActivityCompat.checkSelfPermission(PersonalCenterActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(PersonalCenterActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }

    private void initGuideDate() {
        mguideBeanList = userdao.findPersonalGuidesByUsername(User.USERID);
    }

    //使按返回键时 直接返回旅游攻略主页
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //点击home键
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        //点击返回键
        else if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(PersonalCenterActivity.this, GuidesMainActivity.class);
            startActivity(intent);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
